package com.blb.eduuserservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.common.entity.User;
import com.blb.eduuserservice.config.WXConfigurationProperties;
import com.blb.eduuserservice.mapper.UserMapper;
import com.blb.eduuserservice.service.WxLoginService;
import com.blb.eduuserservice.util.HttpClientUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;

@Slf4j
@Service
public class WxLoginServiceImpl implements WxLoginService {

    @Autowired
    private WXConfigurationProperties wxConfig;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(String code) {
        log.info("code:{}",code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        url = String.format(url,wxConfig.getAppId(),wxConfig.getAppSecret(),code);
        try {
            String token = HttpClientUtils.get(url);
            log.info("token:{}",token);
            Map<String,String> map = new ObjectMapper().readValue(token, Map.class);
            String access_token = map.get("access_token");
            String openid = map.get("openid");
            User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getOpenid,openid));
            if(user == null) {
                String url2 = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s", access_token, openid);
                String userInfo = HttpClientUtils.get(url2);
                log.info("userinfo:{}", userInfo);
                Map<String, String> userMap = new ObjectMapper().readValue(userInfo, Map.class);
                user = new User();
                user.setNickname(userMap.get("nickname"));
                user.setIcon(userMap.get("headimgurl"));
                user.setOpenid(userMap.get("openid"));
                userMapper.insert(user);
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
